<?php
$loader->requireOnce('includes/Icd10Selector/Icd10Selector.class.php');

class C_Prescription extends Controller {
    var $template_mod;
    const REEXAM_NUM_LIMITED = 15;

    function C_Prescription($template_mod = "general") {
        parent::Controller();
        $this->template_mod = $template_mod;
        $this->logger = LoggerManager::getLogger('controllers.C_Prescription');
    }
   
    ///////////////////////////////////////////////////////////////////
    /*
     * 	 	PRESCRIPTION TEMPLATE FUNCITONS
     *
     */
    
    function actionViewAllTemplates(){
        return $this->view->render("display_templates.html");
    }
    
    function actionListTemplate() {
        $obj = Celini::newORDO('PrescriptionTemplate');
        $templates = $obj->listTemplates($this->_me->get_person_id());
        $this->assign('templates', $templates);
        return $this->view->render('list_template.html');
    }

    function actionAddTemplate() {
        $newForm = '';
        $idList = array();
        for ($i = 0; $i < 7; $i++){
            $newForm = $newForm.$this->buildEmptyItemsResponse($i, 'no', 'error_addTemplate');
            array_push($idList, $i);
        }
        $newForm = $newForm.$this->buildEmptyTemplateInfo();
        $newForm = $newForm."<input type='hidden' id='row_id_list' value='".implode(';',$idList)."'>";
        $this->assign('templateBody', $newForm);
        return $this->view->render('edit_template.html');
    }

    function actionSaveTemplateAjax() {
        $result = array(
	       'error'     =>   array('code'=>CoreErrorCode::NORMAL,'mess'=>''),
            'result'   =>   '')
        ;

        //validate
        $phaDrugMaterialObj = Celini::newOrdo('DrugMaterial');
        $errorDrug = array();
        for ($index = 0; $index < 7; $index++) {
            $itemData = $_POST['prescriptionItem_' . $index];
            if (trim($itemData['medicine_name']) != ''
            && !$phaDrugMaterialObj->isExist($itemData['medicine_id'], trim($itemData['medicine_name']))) {
                $errorDrug[] =  trim($itemData['medicine_name']);
            }
        }

        if (count($errorDrug)) {
            $result['error']['code'] = 'Fail';
            $result['error']['mess'] = $errorDrug;
            return json_encode($result);
        }

        // 1. add/update template meta
        $template = $_POST['template'];
        $templateId = trim($template['template_id']);
        $template['doctor_id'] = $this->_me->get_person_id();
        
        $tplObj = Celini::newOrdo('PrescriptionTemplate');
        $tplObj->setup($templateId);
        if ($templateId > 0) {
            $tplObj->updateTemplate($template);
        } else {
            $templateId = $tplObj->addNewTemplate($template);
        }
                 
        // 2. add template detail
        // 2.1 Delete first
        $tmpItemObj = Celini::newOrdo('TemplateItem');
        $tmpItemObj->delete($templateId);

        for ($index = 0; $index < 7; $index++) {
            $itemData = $_POST['prescriptionItem_' . $index];
            if ($itemData['medicine_id'] != ''
                && trim($itemData['medicine_name']) != ''
                && $phaDrugMaterialObj->isExist($itemData['medicine_id'], trim($itemData['medicine_name']))) {
                    $itemData['template_id'] = $templateId;
                    $tmpItemObj = Celini::newOrdo('TemplateItem');
                    $tmpItemObj->addNewTemplateItem($itemData);
            }
        }
         
        $result['result']['template_id'] = $templateId;
         
        return json_encode($result);
    }
    
    function actionRemoveTemplate(){
        $templateId = $_POST['templateId'];
        if ($templateId > 0) {
            $obj = Celini::newORDO('PrescriptionTemplate');
            $obj->removeTemplate($templateId);
        }
    }
    
    function actionEditTemplate($templateId = 0){
        if (isset($_GET['templateId']) && $_GET['templateId'] > 0) {
            $templateId = $_GET['templateId'];
        }
        
        $tplObj = Celini::newORDO('PrescriptionTemplate');
        $template = $tplObj->getTemplate($templateId);
        
        $tplItemObj = Celini::newORDO('TemplateItem');
        $prescriptionItems = $tplItemObj->getTemplateItems($templateId);
        
        // Build table for new template
        $form = '';
        $idList = array();
        for ($i = 0; $i < 7; $i++){
            if (isset( $prescriptionItems[$i])) {
                $form = $form . $this->buildFullItemsResponse($i, '', '', $prescriptionItems[$i]);
                array_push($idList, $i);
            } else {
                $form = $form . $this->buildEmptyItemsResponse($i, '', '');
                array_push($idList, $i);
            }
        }
        
        $form = $form.$this->buildFullTemplateInfo($template);
        $form = $form."<input type='hidden' id='row_id_list' value='".implode(';',$idList)."'>";
        
        $this->assign('templateId', $templateId);
        $this->assign('templateBody', $form);
        return $this->view->render('edit_template.html');
    }
    
    
    //////////////////////////////////////////////////////////////////////
    
    //---------------- END PRESCRIPTION TEMPLATE FUNCTION --------------//
    
    //////////////////////////////////////////////////////////////////////
    
    function actionGetNewForm(){
        // Build table for new template
        $result = array();
        $newForm = '';
        $idList = array();
        switch ($_GET['type']){
            case 'template':
                for ($i = 0; $i < 7; $i++){
                    $newForm = $newForm.$this->buildEmptyItemsResponse($i, 'no', 'error_addTemplate');
                    array_push($idList, $i);
                }
                $newForm = $newForm.$this->buildEmptyTemplateInfo();
                break;
            case 'prescription':
                for ($i = 0; $i < 7; $i++){
                    $newForm = $newForm.$this->buildEmptyItemsResponse($i, 'no', 'error_addPrescription');
                    array_push($idList, $i);
                }
                $newForm = $newForm.$this->buildEmptyPrescriptionInfo();
                break;
        }
        $result['newForm'] = $newForm . "<input type='hidden' id='row_id_list' value='".implode(';',$idList)."'>";
        
        // Doctor and Diagnosis        
        $encounter  =   Celini::newOrdo('EmrGeneralExamination2')->getObjectFromRecordId($_GET['recordId']);
        $result['emr'] = array(
            'doctorId'  => $encounter->get('doctor_id'),
            'doctorName'=> $encounter->getDoctorName(),
            'diagnosis' => $encounter->get('diagnosis'));
        
        
        return json_encode($result);
    }

    
    /**
     * Called from medical record page
     */
    function actionEditPrescription(){
        $obj = Celini::newORDO('Prescription');
        $recordId = $_GET['recordId'];
                
        $noteList = Celini::newORDO('PrescriptionNote')->listAvailableNotes();
        $this->assign('noteList', $noteList);
                     
        $obj = Celini::newORDO('PrescriptionTemplate');
        $templates = $obj->listTemplates($this->_me->get_person_id());
        $this->assign('templates', $templates);
        
        $prescriptionObj = Celini::newOrdo('Prescription');
        $prescriptionList = $prescriptionObj->listPrescriptions($recordId);
        foreach ($prescriptionList as &$row) {
            $row['date_formatted'] = L10nHelper::renderDateTime($row['date'], 'short', 'date');
        }
        $this->assign('prescriptionList', $prescriptionList);
        $this->assign('recordId', $recordId);                
        
        return $this->view->render('edit_prescription.html');
    }

    function actionLoadPrescriptionsAjax() {
        $result = array( 'error'    =>
                            array('code'    => CoreErrorCode::NORMAL,
                            	  'mess'    => ''),
        				 'result' =>
                            array());

        $prescriptionId = $_POST['prescriptionId'];
        $prescriptionObj = Celini::newORDO('Prescription');
        $prescription = $prescriptionObj->getPrescription($prescriptionId);

        if (isset($prescription['date'])) {
            $prescription['date'] = L10nHelper::renderDateTime($prescription['date'], 'short', 'date');
        }
        $presItemObj = Celini::newORDO('PrescriptionItem');
        $prescriptionItems = $presItemObj->getPrescriptionItems($prescriptionId);

        // Build table for new template
        $form = ''; $idList = array();
        for ($i = 0; $i < 7; $i++){
            if (isset( $prescriptionItems[$i])) {
                $form = $form . $this->buildFullItemsResponse($i, '', '', $prescriptionItems[$i]);
                array_push($idList, $i);
            } else {
                $form = $form . $this->buildEmptyItemsResponse($i, '', '');
                array_push($idList, $i);
            }
        }
        $form = $form.$this->buildFullPrescriptionInfo($prescription);
        $form = $form."<input type='hidden' id='row_id_list' value='".implode(';',$idList)."'>";
        $result['result']['form'] = $form;
        $result['result']['diagnosis'] = $prescription['diagnosis'];
        $result['result']['prescription_id'] = $prescription['prescription_id'];
        $result['result']['doctor_id'] = $prescription['doctor_id'];
        $result['result']['doctor_name'] = Celini::newORDO('Employee', $prescription['doctor_id'])->get('name');
      
        return json_encode($result);
    }
    
    function actionDeletePrescriptionAjax() {
         $result = array(
           'error'     =>   array('code'=>CoreErrorCode::NORMAL,'mess'=>''),
            'result'   =>   '')
        ;
        $prescriptionId = $_POST['prescriptionId'];
        if (!isset($_POST['prescriptionId']) || trim($_POST['prescriptionId']) == '') {
            return json_encode($result);
        }
        $prescriptionObj = Celini::newOrdo('Prescription');
        $result['result'] = $prescriptionObj->delete($prescriptionId);
        return json_encode($result);
    }

    function actionSavePrescriptionAjax() {
        $result = array(
	       'error'     =>   array('code'=>CoreErrorCode::NORMAL,'mess'=>''),
            'result'   =>   '')
        ;                
        
        //validate first
        $phaDrugMaterialObj = Celini::newOrdo('DrugMaterial');
        $errorDrug = array();
        
        
        for ($index = 0; $index < 7; $index++) {
            $itemData = $_POST['prescriptionItem_' . $index];
            $itemData['medicine_name'] = Utils::sanitizeText($itemData['medicine_name']);
            if ($itemData['medicine_name'] != ''
                    && !$phaDrugMaterialObj->isExist($itemData['medicine_id'], $itemData['medicine_name'])) {
                $errorDrug[] =  $itemData['medicine_name'];
            }
        }
        
        if (count($errorDrug) > 0) {
            $result['error']['code'] = 'Fail';
            $result['error']['mess'] = $errorDrug;
            return json_encode($result);
        }
                             
        $pres = $_POST['prescription'];
        $presId = trim($pres['prescription_id']);
        $presObj = Celini::newOrdo('Prescription');
        $presObj->setup($presId);
        if ($presId > 0) {
            $presId = $presObj->updatePrescription($pres);
        } else {
            $presId = $presObj->addNewPrescription($pres);
        }
         
        //add pres detail
        //remove all first
        
        $presItemObj = Celini::newOrdo('PrescriptionItem');
        $presItemObj->delete($presId);

        // add prescription item
        for ($index = 0; $index < 7; $index++) {
            $itemData = $_POST['prescriptionItem_' . $index];
            $itemData['medicine_name'] = Utils::sanitizeText($itemData);
            if ($itemData['medicine_id'] != '' && $itemData['medicine_name'] != '' ) {
                $itemData['prescription_id'] = $presId;
                $presItemObj = Celini::newOrdo('PrescriptionItem');
                $presItemObj->addNewPrescriptionItem($itemData);
            }
             
        }
         
        // Render prescription selectbox
        $prescriptionObj = Celini::newOrdo('Prescription');
        $prescriptionList = $prescriptionObj->listPrescriptions($pres['medical_record_id']);
        $html = '<option value="0">----' . L10nHelper::_('Select prescription') . '----</option>';
        foreach ($prescriptionList as &$row) {
            $row['date_formatted'] = L10nHelper::renderDateTime($row['date'], 'short', 'date');
            if ($presId ==  $row['prescription_id'] ) {
                $html .= '<option value="' . $row['prescription_id'] . '" selected="selected">' . $row['date_formatted'] . ' ' . $row['doctor_name'] . '</option>';
            } else {
                $html .= '<option value="' . $row['prescription_id'] . '" >' . $row['date_formatted'] . ' ' . $row['doctor_name'] . '</option>';

            }
        }
                
        $result['result']['prescription_id'] = $presId;
        $result['result']['prescription_form'] = $html;               
        
        return json_encode($result);
    }


    function actionImportTemplate() {
        $templateId = $_POST['templateId'];
        $prescriptionId = $_POST['prescriptionId'];
        
        $tplItemObj = Celini::newORDO('TemplateItem');
        $prescriptionItems = $tplItemObj->getTemplateItems($templateId);
        
        // Build table for new template
        $form = '';
        $idList = array();
        for ($i = 0; $i < 7; $i++){
            if (isset( $prescriptionItems[$i])) {
                $form = $form . $this->buildFullItemsResponse($i, '', '', $prescriptionItems[$i]);
                array_push($idList, $i);
            } else {
                $form = $form . $this->buildEmptyItemsResponse($i, '', '');
                array_push($idList, $i);
            }
        }

        if ($prescriptionId > 0) {
            $prescription = Celini::newOrdo('Prescription')->getPrescription($prescriptionId);
            $form = $form . $this->buildFullPrescriptionInfo($prescription);
        } else {
            $form = $form . $this->buildEmptyPrescriptionInfo();
        }
        
        $form = $form . "<input type='hidden' id='row_id_list' value='".implode(';',$idList)."'>";
        
        return $form;
    }

    private function buildEmptyTemplateInfo(){
        $res =
			"<tr>".
				"<td align='right'>" . L10nHelper::_("Prescription template name") . " (*)</td>".
				"<td colspan='5'>".
					"<input type='text' id='templateName' name='template[name]' value=''>".
				"</td>".
			"</tr>".
			"<tr class='last'>".
				"<td align='right'>" . L10nHelper::_("Description") . "</td>".
				"<td colspan='5'>".
					"<textarea cols=40 rows=2 id='templateDescription' name='template[description]' value=''></textarea>".
				"</td>".
			"</tr>";
        return $res;
    }

    private function buildFullTemplateInfo($template){
        
        $res =
			"<tr>".
				"<td align='right'>" . L10nHelper::_("Prescription template name") . " (*)</td>".
				"<td colspan='5'>".
					"<input type='text' id='templateName' name='template[name]' value='{$template['template_name']}'>".
				"</td>".
			"</tr>".
			"<tr class='last'>".
				"<td align='right'>" . L10nHelper::_("Description") . "</td>".
				"<td colspan='5'>".
					"<textarea cols=40 rows=2 id='templateDescription' name='template[description]'>{$template['note']}</textarea>".
				"</td>".
			"</tr>";
        return $res;
    }
    
    
    private function buildEmptyPrescriptionInfo(){
        $numList = $this->getNumList();
        $optionList = $this->getOptionList();

        $res =
			"<tr>
				<td align='right'>
					<input type='button' style='margin-right: 10px' value='" . L10nHelper::_("Advice") . "' onClick='showRecommendation()'>
				</td>
				<td colspan='5'>
					<textarea cols=40 rows=2 id='note_input' name='prescription[note]' value=''></textarea>
				</td>
			</tr>
			<tr class='last'>
				<td align='right'>" . L10nHelper::_("Appointment date") . "</td>
				<td colspan='5'>
					" . L10nHelper::_("After") . " &nbsp; $numList &nbsp; $optionList <input type='text' id='re_examine_input' name='prescription[re_examine]' value='' >
				</td>
			</tr>";
        return $res;
    }
    
    private function buildFullPrescriptionInfo($prescription){
        $numList = $this->getNumList();
        $optionList = $this->getOptionList();

        $res =
            "<tr>
                <td align='right'>
                    <input type='button' style='margin-right: 10px' value='" . L10nHelper::_("Advice") . "' onClick='showRecommendation()'>
                </td>
                <td colspan='5'>
                    <textarea cols=40 rows=2 id='note_input' name='prescription[note]' >" . $prescription['note'] ."</textarea>
                </td>
            </tr>
            <tr class='last'>
                <td align='right'>" . L10nHelper::_("Appointment date") . "</td>
                <td colspan='5'>
                    " . L10nHelper::_("After") . " &nbsp; $numList &nbsp; $optionList <input type='text' id='re_examine_input' name='prescription[re_examine]' value='" . $prescription['re_examine'] ."' >
                </td>
            </tr>";
        return $res;
    }

    private function buildSelectBox($arr, $id, $name = '', $v = '') {

        $select = "<select id='$id' name='$name' style='width: 60px' >";
        $select .= "<option value='0'>&nbsp;</option>";
        foreach ($arr as $key=>$value) {
            if ($key == $v) {
                $select .= "<option value='" . $key . "' selected='selected'>" . $value ."</option>";
            } else {
                $select .= "<option value='" . $key . "' >" . $value ."</option>";
            }
        }
        $select .= "</select>";
        return $select;
    }

    private function buildEmptyItemsResponse($i, $empty, $errorDiv){
        $arrEnumUnit = Utils::getEnumArrayKey(EnumerationConstant::PHA_IMSE_UNIT);
        $arrEnumUs = Utils::getEnumArrayKey(EnumerationConstant::PHA_DM_DEFAULT_USAGE);
         
        $uSelectBox = $this->buildSelectBox($arrEnumUs, $i . "_usage_title", "prescriptionItem_".$i ."[usage_title]");
        $dSelectBox = $this->buildSelectBox($arrEnumUnit, $i . "_dosage_title", "prescriptionItem_".$i ."[dosage_title]");
        $qSelectBox = $this->buildSelectBox($arrEnumUnit,$i . "_quantity_title", "prescriptionItem_".$i ."[quantity_title]");
        $res = "<tr id='".$i."_item'>".
				"<td>".
					"<input type='text' style='width: 180px' id='" .$i ."_medicine_name_input' name='prescriptionItem_".$i ."[medicine_name]' value='' onblur='javascript:validateDrug(" . $i . ")' />".
		            "<input type='hidden' id='" .$i ."_medicine_id_hidden' name='prescriptionItem_".$i ."[medicine_id]' value='' />".

				"</td>".
				"<td>"
				. L10nHelper::_("Every day %s time(s)", $uSelectBox .
                    "&nbsp<input style='width: 20px;' type='text' id='" .$i ."_usage_num_input' name='prescriptionItem_".$i ."[usage_num]' value='' onblur='javascript:computeTotal(" . $i . ")' />")
				.
				"</td>".
				"<td>"
				. L10nHelper::_("Every time %s",
					"<input style='width: 20px;' type='text' id='" .$i ."_dosage_input' name='prescriptionItem_".$i ."[dosage]' value='' onblur='javascript:computeTotal(" . $i . ")' />".
		            "&nbsp" . $dSelectBox) .
				"</td>".
				"<td>".
					"<input style='width: 20px;' type='text' id='" .$i ."_time_input' name='prescriptionItem_".$i ."[time]' value='' onblur='javascript:computeTotal(" . $i . ")' />".
					" " . L10nHelper::_("day") .
				"</td>".
				"<td>".
					"<input style='width: 20px;' type='text' id='" .$i ."_quantity_num_input' name='prescriptionItem_".$i ."[quantity_num]' value=''  onfocus='javascript:computeTotal(" . $i . ")' />".
					"&nbsp" . $qSelectBox .
				"</td>".
				"<td>".
					"<input type='text' style='width: 230px' id='" .$i ."_note' name='prescriptionItem_".$i ."[note]' value='' onblur='javascript:completeNote(" . $i . ")'/>".
				"</td>".
			"</tr>";
				return $res;
    }

    private function buildFullItemsResponse($i, $empty, $errorDiv, $item){
        $arrEnumUnit = Utils::getEnumArrayKey(EnumerationConstant::PHA_IMSE_UNIT);
        $arrEnumUs = Utils::getEnumArrayKey(EnumerationConstant::PHA_DM_DEFAULT_USAGE);

        $uSelectBox = $this->buildSelectBox($arrEnumUs, $i . "_usage_title", "prescriptionItem_".$i ."[usage_title]", $item['usage_title']);
        $dSelectBox = $this->buildSelectBox($arrEnumUnit, $i . "_dosage_title", "prescriptionItem_".$i ."[dosage_title]", $item['dosage_title']);
        $qSelectBox = $this->buildSelectBox($arrEnumUnit,$i . "_quantity_title", "prescriptionItem_".$i ."[quantity_title]", $item['quantity_title']);
                       
        $res = "<tr id='".$i."_item'>".
                "<td>".
                    "<input type='text' style='width: 180px' id='{$i}_medicine_name_input' name='prescriptionItem_".$i ."[medicine_name]' value='{$item['medicine_name']}' onblur='javascript:validateDrug({$i})'/>".
                    "<input type='hidden' id='" .$i ."_medicine_id_hidden' name='prescriptionItem_".$i ."[medicine_id]' value='" . $item['medicine_id'] ."' />".

                "</td>".
                "<td>"
                . L10nHelper::_("Every day %s time(s)", $uSelectBox .
                    "&nbsp<input style='width: 20px;' type='text' id='" .$i ."_usage_num_input' name='prescriptionItem_".$i ."[usage_num]' value='" . $item['usage_num'] ."' onblur='javascript:computeTotal(" . $i . ")'/>")
                .
                "</td>".
                "<td>"
                . L10nHelper::_("Every time %s",
                    "<input style='width: 20px;' type='text' id='" .$i ."_dosage_input' name='prescriptionItem_".$i ."[dosage]' value='" . $item['dosage'] ."' onblur='javascript:computeTotal(" . $i . ")'/>".
                    "&nbsp" . $dSelectBox) .
                "</td>".
                "<td>".
                    "<input style='width: 20px;' type='text' id='" .$i ."_time_input' name='prescriptionItem_".$i ."[time]' value='" . ($item['time']==0?'':$item['time']) ."' onblur='javascript:computeTotal(" . $i . ")'/>".
                    " " . L10nHelper::_("day") .
                "</td>".
                "<td>".
                    "<input style='width: 20px;' type='text' id='" .$i ."_quantity_num_input' name='prescriptionItem_".$i ."[quantity_num]' value='" . $item['quantity_num'] ."' onFocus=\"computeTotal('" .$i ."')\" />".
                    "&nbsp" . $qSelectBox .
                "</td>".
                "<td>".
                    "<input type='text' style='width: 230px' id='" .$i ."_note' name='prescriptionItem_".$i ."[note]' value='" . $item['note'] ."' onblur='javascript:completeNote(" .$i .")' />".
                "</td>".
            "</tr>";
                return $res;
    }

    private function getNumList() {
        $numList = "<select id='num_list' onchange='changeNumList()'>
			<option value='0' label='---'>---</option>
			<option value='khican' label='" . L10nHelper::_("When needed") . "'>" . L10nHelper::_("When needed") . "</option>";
        for ($i = 1; $i <= self::REEXAM_NUM_LIMITED; $i++) {
            $numList .= "<option value='$i' label='$i'>$i</option>";
        }
        $numList .=
				"</select>";
        return $numList;
    }

    private function getOptionList() {
        $optionList =
			"<select id='option_list' onchange='changeOptionList()'>
				<option value='day' label='" . L10nHelper::_("Day") . "'>" . L10nHelper::_("Day") . "</option>
				<option value='week' label='" . L10nHelper::_("Week") . "'>" . L10nHelper::_("Week") . "</option>
				<option value='month' label='" . L10nHelper::_("Month") . "'>" . L10nHelper::_("Month") . "</option>
			</select>";
        return $optionList;
    }

    public function actionGetLatestPrescription($patientId = ''){
        if(isset($_GET['patientId'])){
            $patientId	=	(int)$_GET['patientId'];
        }
        $this->assign_by_ref('person', Celini::newORDO('Person', $patientId));
        $this->assign_by_ref('patient', Celini::newORDO('Patient', $patientId));
        $objPres	=	ORDataObject::factory('Prescription')->getLatestObjectByPatientId($patientId);
        if(isset($objPres)&& $objPres!=''){
            $recordId	=	$objPres->get('medical_record_id');
            // Get current prescription_id of this patient
            $commonInfo = ORDataObject::factory('EncounterCommonInfo');
            $commonInfo = $commonInfo->getObjectFromRecordId($recordId);
            $prescriptionId = $objPres->get_id();
            $diagnosis = Celini::newORDO('Encounter')->getObjectFromRecordId($recordId);
             
            // Get prescription items
            $presItem = Celini::newORDO('PrescriptionItem');
            $prescriptionItems = $presItem->getPrescriptionItems($prescriptionId);
             
            // Get other info, including note, re_examine, name (doctor_name)
            $other = $objPres->getPrescription($prescriptionId);
            $person = Celini::newORDO('Person');
            $doctor = $person->getNameById($other['doctor_id']);
             
            $other['name'] = '';
            if(isset($doctor['name'])) {
                $other['name'] = $doctor['name'];
            }
            // TODO: @LOCALIZATION
            $other['printTime'] = date('d/m/Y H:i');
            $this->assign('i', 1);
            $this->assign_by_ref('presItem', $prescriptionItems);
            $this->assign_by_ref('info', $other);
            $this->assign_by_ref('diagnosis', $diagnosis);
            $this->assign_by_ref('commonInfo', $commonInfo);
            $this->assign('recordId', $recordId);
        }
        return $this->view->render("prescription_print_view.html");
    }
    
    ////////////////////////// TO-BE DELETED FUNCTIONS ///////////////////////////
    function actionGetAllMedicineNames(){
        $obj = Celini::newORDO('Medicine');
        $q = strtolower($_GET['q']);
        if (!$q || strlen($q) < 1) return;
        $names = $obj->getMedicineSuggestionNames($q);
        foreach ($names as $value) {
            echo "$value\n";
        }
    }
    
     public function actionViewPrescriptionAjax() {
        $message = "<div style='padding: 10px'><span class='label'>" . L10nHelper::_("There is not a prescription in this service ticket") . "</span></div>";

        // Get ticket_id from ticket_item_id
        $ticketItem = Celini::newORDO('TicketItem', $_GET['ticketItemId']);
        $ticketId = $ticketItem->get('ticket_id');

        // Get record from ticket
        $record = Celini::newORDO('MedicalRecord');
        $recordId = $record->getRecordIdFromTicket($ticketId);
        if ($recordId == false) return $message;

        // Get current prescription_id of this patient
        $pres = Celini::newORDO('Prescription');
        $prescriptionId = $pres->getPrescriptionIdFromRecord($recordId);
        if ($prescriptionId == false) return $message;

        // Get prescription items
        $presItem = Celini::newORDO('PrescriptionItem');
        $prescriptionItems = $presItem->getPrescriptionItems($prescriptionId);

        // Get other info, including note, re_examine, name (doctor_name)
        $other = $pres->getPrescription($prescriptionId);
        $person = Celini::newORDO('Person');
        $doctor = $person->getNameById($other['doctor_id']);
        $other['name'] = $doctor['name'];

        // Build response
        return $this->buildReadOnlyPrescription($prescriptionItems, $other);
    }
    
private function buildReadOnlyPrescription($prescriptionItems, $other){
        $bottomNote = 'no';
        $response = "<div><table cellspacing='0' cellpadding='0' class='grid'>".
						"<tr>
							<th class=\"first\">" . L10nHelper::_("Medicine name") . "</th>
							<th>" . L10nHelper::_("Usage") . "</th>
							<th>" . L10nHelper::_("Dosage") . "</th>
							<th>" . L10nHelper::_("Period time") . "</th>
							<th>" . L10nHelper::_("Quantity") . "</th>
							<th>" . L10nHelper::_("Description") . "</th>
							<th>" . L10nHelper::_("Price") . "</th>
							<th class=\"last\">" . L10nHelper::_("Medicial insuarance") . "</th>
						</tr>";
        if (empty($prescriptionItems)){
            $response = $response."<tr><td>" . L10nHelper::_("Don't have a medicine in prescription yet.") . "</td></tr>";
        } else {
            foreach ($prescriptionItems as $prescriptionItem){
                if ($prescriptionItem['insurance_support'] == 'no'){
                    $medicine = "<i>".$prescriptionItem['medicine_name']."</i>";
                    $bottomNote = 'yes';
                } else $medicine = $prescriptionItem['medicine_name'];
                if ($prescriptionItem['medicine_id'] != ''){
                    if($prescriptionItem['insurance_support']=='yes'){
                        $insSupport	=	L10nHelper::_("Yes");
                    }
                    else{
                        $insSupport	=	L10nHelper::_("No");
                    }
                    $response = $response.
							"<tr>".
								"<td class=\"first\">".$medicine."</td>".
								"<td>".$prescriptionItem['usage_title']." ". $prescriptionItem['usage_num']." ".$prescriptionItem['usage_unit']."/" . L10nHelper::_("Times") . "</td>".
								"<td>".L10nHelper::_("%s&nbsp;times/day",$prescriptionItem['dosage']) . "</td>".
								"<td>".L10nHelper::_("%s&nbsp;day(s)",$prescriptionItem['time']) . "</td>".
								"<td>".$prescriptionItem['quantity_num']." ".$prescriptionItem['quantity_title']."</td>".
								"<td>".$prescriptionItem['note']."&nbsp;</td>".
								"<td>".$prescriptionItem['price']."&nbsp;</td>".
								"<td class=\"last\">".$insSupport."&nbsp;</td>".
							"</tr>";
                }
            }
        }
        $response .=    "<tr>".
							"<td class=\"first last\">" . L10nHelper::_("Advice") . "</td>
							 <td colspan=\"7\" class=\"last\">".$other['note']."&nbsp;</td>".
						"</tr>".
						"<tr>".
							"<td class=\"first last\">" . L10nHelper::_("Re-examination") . "</td>
							<td colspan=\"7\" class=\"last\">".$other['re_examine']."&nbsp;</td>".
						"</tr>".
						"<tr>".
							"<td class=\"first last\">" . L10nHelper::_("Doctor") . "</td>
							<td colspan=\"6\">".$other['name']."&nbsp;</td>
							<td class=\"last\">" . $other['date'] . "&nbsp;</td>".
						"</tr>";
        if ($bottomNote == 'yes'){
            $response .= "<tr>".
							"<td class='first last' colspan='8'>(*)<i>" . L10nHelper::_("Medicines in italic") . "</i>: " . L10nHelper::_("Medicial insurance does not support.") . "</td>".
						"</tr>";
        }
        $response .= "</table></div>";
        return $response;
    }
    
}
?>